/*
Copyright 2025.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controller

import (
	"context"
	"time"

	appsv1 "my-operator/api/v1"

	k8sappsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
)

// FooReconciler reconciles a Foo object
type FooReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

// +kubebuilder:rbac:groups=apps.example.com,resources=foos,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=apps.example.com,resources=foos/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=apps.example.com,resources=foos/finalizers,verbs=update
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;delete
// +kubebuilder:rbac:groups=apps,resources=deployments/status,verbs=get;update;patch

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Foo object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.20.0/pkg/reconcile
func (r *FooReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	_ = log.FromContext(ctx)
	// 获取 Foo 资源
	foo := &appsv1.Foo{}
	if err := r.Get(ctx, req.NamespacedName, foo); err != nil {
		if apierrors.IsNotFound(err) {
			return ctrl.Result{}, nil
		}
		return ctrl.Result{}, err
	}

	// 更新关联的 Deployment 资源
	if err := r.reconcileDeployment(foo); err != nil {
		return ctrl.Result{}, err
	}

	// 更新 Foo 资源的状态
	if err := r.updateFooStatus(foo); err != nil {
		return ctrl.Result{}, err
	}

	return ctrl.Result{}, nil
}

// reconcileDeployment 更新关联的 Deployment 资源
func (r *FooReconciler) reconcileDeployment(foo *appsv1.Foo) error {
	// 创建 Deployment 资源
	desiredDeployment := &k8sappsv1.Deployment{
		ObjectMeta: metav1.ObjectMeta{
			Name:      foo.Name + "-deployment",
			Namespace: foo.Namespace,
			Labels: map[string]string{
				"app": foo.Name,
			},
		},
		Spec: k8sappsv1.DeploymentSpec{
			Replicas: &foo.Spec.Replicas,
			Selector: &metav1.LabelSelector{
				MatchLabels: map[string]string{
					"app": foo.Name,
				},
			},
			Template: corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: map[string]string{
						"app": foo.Name,
					},
				},
				Spec: corev1.PodSpec{
					Containers: []corev1.Container{
						{
							Name:  foo.Name,
							Image: foo.Spec.Image,
						},
					},
				},
			},
		},
	}

	// 设置 Deployment 资源的 OwnerReference
	if err := ctrl.SetControllerReference(foo, desiredDeployment, r.Scheme); err != nil {
		return err
	}

	// 检查 Deployment 资源是否存在
	existingDeployment := &k8sappsv1.Deployment{}
	if err := r.Get(context.TODO(), client.ObjectKeyFromObject(desiredDeployment), existingDeployment); err != nil {
		if apierrors.IsNotFound(err) {
			return r.Create(context.TODO(), desiredDeployment)
		}
		return err
	}

	// 更新 Deployment 资源
	existingDeployment.Spec = desiredDeployment.Spec
	return r.Update(context.TODO(), existingDeployment)
}

// updateFooStatus 更新 Foo 资源的状态
func (r *FooReconciler) updateFooStatus(foo *appsv1.Foo) error {
	// 获取 Deployment 资源
	deployment := &k8sappsv1.Deployment{}
	if err := r.Get(context.TODO(), client.ObjectKey{
		Name:      foo.Name + "-deployment",
		Namespace: foo.Namespace,
	}, deployment); err != nil {
		return err
	}

	foo.Status.ReadyReplicas = deployment.Status.ReadyReplicas
	foo.Status.LastUpdated = metav1.Now().Format(time.RFC3339)
	return r.Status().Update(context.TODO(), foo)
}

// SetupWithManager sets up the controller with the Manager.
func (r *FooReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&appsv1.Foo{}).
		Owns(&k8sappsv1.Deployment{}).
		Named("foo").
		Complete(r)
}
